package com.jxb.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.nacos.common.utils.ExceptionUtil;
import com.jxb.annotations.PreAuthenticated;
import org.apache.skywalking.apm.toolkit.trace.Tag;
import org.apache.skywalking.apm.toolkit.trace.Tags;
import org.apache.skywalking.apm.toolkit.trace.Trace;
import org.apache.skywalking.apm.toolkit.trace.TraceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.jxb.api.OrderFeignService;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    OrderFeignService orderFeignService;

    @PreAuthenticated("permitAll")
    @SentinelResource(value = "/findOrderByUserId/{id}",
            fallback = "fallback",fallbackClass = ExceptionUtil.class,
            blockHandler = "handleException",blockHandlerClass = ExceptionUtil.class
    )
    @RequestMapping(value = "/findOrderByUserId/{id}")
    public Object findOrderByUserId(@PathVariable("id") Integer id) {
        //feign调用
        System.out.println("调用到用户服务--------------------------------");
       Object result = orderFeignService.findOrderByUserId(id);
        return result;
    }

    @GetMapping("/testgateway")
    public String testGateway(HttpServletRequest request) throws Exception {
        System.out.println("gateWay获取请求头X-Request-color："
                                   +request.getHeader("X-Request-color"));
        return "success";
    }
    @GetMapping("/testgateway2")
    public String testGateway(@RequestHeader("X-Request-color") String color) throws Exception {
        System.out.println("gateWay获取请求头X-Request-color："+color);
        return "success";
    }

    @Trace
    @Tags({@Tag(key = "param", value = "arg[0]"),
            @Tag(key = "user", value = "returnedObj")})
    @RequestMapping("/list")
    public List<User> list(){

        //TraceContext可以绑定key-value
        // TraceContext.putCorrelation("name", "fox");
        // Optional<String> op = TraceContext.getCorrelation("name");
        // System.out.println("name = {} "+op.get());
        // //获取追踪的traceId
        // String traceId = TraceContext.traceId();
        // System.out.println("traceId = {} "+traceId);

        List<User> users = new ArrayList<>();
        User user = new User();
        user.setName("123456");
        users.add(user);

        return users;
    }
}